/**
 * @description font-size menu
 * @author wangfupeng
 */

import { IDomEditor, ISelectMenu, DomEditor } from '@wangeditor/editor'
import { Editor } from 'slate'

class ProFontSizeMenu implements ISelectMenu {
  readonly title = '字号'
  readonly iconSvg =
    '<svg viewBox="0 0 1024 1024"><path d="M64 512h384v128h-128V1024h-128V640h-128z m896-256H708.2496v768h-136.4992V256H320V128h640z"></path></svg>'
  readonly mark = 'fontSize'
  readonly tag = 'select'
  readonly width = 80

  getOptions(editor: IDomEditor) {
    const options: Array<{
      text: string
      value: string
      selected?: boolean
    }> = []

    const { fontSizeList = [] } = editor.getMenuConfig(this.mark)

    let defaultValue = ''

    fontSizeList.forEach(
      (size: string | { name: string; value: string }, index) => {
        if (typeof size === 'string') {
          options.push({
            text: size,
            value: size
          })
        } else if (typeof size === 'object') {
          const { name, value } = size
          options.push({
            text: name,
            value: value
          })
        }
        if (index === 0) {
          defaultValue = options[0].value
          options[0].value = ''
        }
      }
    )

    // 设置 selected
    const curValue = this.getValue(editor)
    const curMarks = Editor.marks(editor)
    if (curValue === '' && curMarks && curMarks[this.mark] !== defaultValue) {
      console.log(' editor.addMark')
      editor.addMark(this.mark, defaultValue)
    }

    options.forEach((opt) => {
      if (opt.value === curValue) {
        opt.selected = true
      } else {
        delete opt.selected
      }
    })

    return options
  }

  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor: IDomEditor): boolean {
    return false
  }

  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor: IDomEditor): string | boolean {
    const mark = this.mark
    const curMarks = Editor.marks(editor)
    if (curMarks && curMarks[mark]) return curMarks[mark]
    return ''
  }

  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(editor: IDomEditor): boolean {
    if (editor.selection == null) return true

    const [match] = Editor.nodes(editor, {
      match: (n) => {
        const type = DomEditor.getNodeType(n)
        if (type === 'pre') return true // 代码块
        if (Editor.isVoid(editor, n)) return true // void node

        return false
      },
      universal: true
    })

    // 匹配到，则禁用
    if (match) return true
    return false
  }

  // 点击菜单时触发的函数
  exec(editor: IDomEditor, value: string | boolean) {
    const mark = this.mark
    if (value) {
      editor.addMark(mark, value)
    } else {
      editor.removeMark(mark)
    }
  }
}

const proFontSizeMenuConf = {
  key: 'pro-font-size', // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new ProFontSizeMenu()
  }
}

export default proFontSizeMenuConf
